<template>
  <div class="medicines-market">
    <!-- 药品商城主内容区 -->
    <div v-if="activeTab === 'medicines'">
      <div class="market-toolbar">
        <el-dropdown class="toolbar-dropdown">
          <el-button class="toolbar-btn" type="default" plain>
            <el-icon><arrow-down /></el-icon> 筛选
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="selectedCategory = ''">全部</el-dropdown-item>
              <el-dropdown-item v-for="category in categories" :key="category" @click="selectedCategory = category">{{ category }}</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-dropdown class="toolbar-dropdown">
          <el-button class="toolbar-btn" type="default" plain>
            <el-icon><arrow-down /></el-icon> 排序
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="sortBy = 'default'">默认</el-dropdown-item>
              <el-dropdown-item @click="sortBy = 'priceAsc'">价格升序</el-dropdown-item>
              <el-dropdown-item @click="sortBy = 'priceDesc'">价格降序</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-input
          v-model="searchQuery"
          placeholder="局部搜索"
          class="toolbar-search"
          @input="handleSearch"
          clearable
        >
          <template #suffix>
            <el-icon><search /></el-icon>
          </template>
        </el-input>
        <el-button class="toolbar-btn order-btn" type="primary" @click="goToOrders">
          <el-icon><Document /></el-icon> 我的订单
        </el-button>
        <el-button class="toolbar-btn cart-btn" type="primary" @click="goToCart">
          <el-icon><ShoppingCart /></el-icon> 购物车
          <el-badge v-if="cartItemCount" :value="cartItemCount" class="cart-badge" />
        </el-button>
      </div>
      <!-- 商品列表 -->
      <el-row :gutter="24" class="market-list">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="medicine in displayMedicines" :key="medicine.id">
          <el-card class="market-card" shadow="hover">
            <div class="market-fav-float" @click.stop="toggleFavorite(medicine)">
              <el-icon :class="['fav-float-icon', isFavorited(medicine) ? 'active' : '']">
                <component :is="isFavorited(medicine) ? StarFilled : Star" />
              </el-icon>
            </div>
            <div class="market-img-wrap">
              <img :src="medicine.image" :alt="medicine.name" />
            </div>
            <div class="market-info">
              <div class="market-title">{{ medicine.name }}</div>
              <div class="market-price-row">
                <span class="market-price">¥{{ medicine.price.toFixed(2) }}</span>
                <span v-if="medicine.originPrice && medicine.originPrice > medicine.price" class="market-origin">¥{{ medicine.originPrice }}</span>
              </div>
              <div class="market-btn-row">
                <el-button type="primary" size="small" class="market-cart-btn" @click="addToCart(medicine)" :disabled="medicine.stock <= 0">加入购物车</el-button>
                <el-button size="small" class="market-detail-btn" @click="showMedicineDetail(medicine)">详情</el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <!-- 分页器 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="totalMedicines"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
        />
      </div>
      <!-- 药品详情对话框（含收藏按钮） -->
      <el-dialog
        :title="selectedMedicine ? selectedMedicine.name : ''"
        v-model="dialogVisible"
        width="700px"
        class="detail-dialog-root"
      >
        <div v-if="selectedMedicine" class="detail-dialog">
          <div class="detail-left">
            <img :src="selectedMedicine.image" :alt="selectedMedicine.name" />
          </div>
          <div class="detail-right">
            <h2 class="detail-title">{{ selectedMedicine.name }}</h2>
            <div class="detail-price-row">
              <span class="detail-price">¥{{ selectedMedicine.price.toFixed(2) }}</span>
              <span v-if="selectedMedicine.originPrice && selectedMedicine.originPrice > selectedMedicine.price" class="detail-origin">¥{{ selectedMedicine.originPrice }}</span>
            </div>
            <div class="detail-tags">
              <el-tag size="small" type="info">类别：{{ selectedMedicine.category }}</el-tag>
              <el-tag size="small" type="success">库存：{{ selectedMedicine.stock }}件</el-tag>
              <el-tag size="small" type="warning">厂家：{{ selectedMedicine.manufacturer }}</el-tag>
              <el-tag size="small" type="">规格：{{ selectedMedicine.specification }}</el-tag>
            </div>
            <div class="detail-actions">
              <el-input-number
                v-model="purchaseQuantity"
                :min="1"
                :max="selectedMedicine.stock"
                size="small"
              />
              <el-button type="primary" @click="addToCart(selectedMedicine, purchaseQuantity)">
                加入购物车
              </el-button>
              <el-button class="fav-btn" link @click="toggleFavorite(selectedMedicine)">
                <el-icon :class="['fav-icon', isFavorited(selectedMedicine) ? 'active' : '']">
                  <component :is="isFavorited(selectedMedicine) ? StarFilled : Star" />
                </el-icon>
                <span class="fav-text" :class="{active: isFavorited(selectedMedicine)}">
                  {{ isFavorited(selectedMedicine) ? '已收藏' : '收藏' }}
                </span>
              </el-button>
            </div>
            <div class="detail-desc-card">
              <h3>产品说明</h3>
              <p>{{ selectedMedicine.description }}</p>
              <div v-if="selectedMedicine.usage" class="detail-usage">用法用量：{{ selectedMedicine.usage }}</div>
            </div>
          </div>
        </div>
      </el-dialog>
    </div>
    <!-- 我的订单页面美化和完善 -->
    <div v-else-if="activeTab === 'orders'">
      <div class="orders-page">
        <div class="orders-toolbar">
          <el-button type="primary" class="back-btn" @click="activeTab = 'medicines'">
            返回药品商城
          </el-button>
          <el-radio-group v-model="statusFilter" @change="fetchOrders">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button label="pending">待付款</el-radio-button>
            <el-radio-button label="paid">待发货</el-radio-button>
            <el-radio-button label="shipped">待收货</el-radio-button>
            <el-radio-button label="completed">已完成</el-radio-button>
            <el-radio-button label="cancelled">已取消</el-radio-button>
          </el-radio-group>
          <el-input v-model="orderSearchQuery" placeholder="搜索订单号/商品" @input="handleOrderSearch" clearable class="orders-search">
            <template #prefix><el-icon><search /></el-icon></template>
          </el-input>
        </div>
        <el-empty v-if="!filteredOrders.length" description="暂无订单" />
        <el-row v-else :gutter="24">
          <el-col :span="24" v-for="order in pagedOrders" :key="order.id">
            <el-card class="order-card">
              <div class="order-header">
                <span>订单号：{{ order.id }}</span>
                <el-tag :type="getStatusType(order.status)">{{ getStatusText(order.status) }}</el-tag>
                <span class="order-time">下单时间：{{ formatDate(order.createTime) }}</span>
              </div>
              <div class="order-items">
                <div v-for="item in order.items" :key="item.id" class="order-item">
                  <img :src="item.image" :alt="item.name" class="item-image" />
                  <div class="item-info">
                    <div class="item-name">{{ item.name }}</div>
                    <div class="item-quantity">数量：{{ item.quantity }}</div>
                    <div class="item-price">单价：¥{{ item.price.toFixed(2) }}</div>
                    <div class="item-subtotal">小计：¥{{ (item.price * item.quantity).toFixed(2) }}</div>
                  </div>
                </div>
              </div>
              <div class="order-footer">
                <div class="order-summary">
                  <span>实付金额：</span>
                  <span class="order-amount">¥{{ (order.totalAmount ?? order.total ?? 0).toFixed(2) }}</span>
                </div>
                <div class="order-actions">
                  <el-button v-if="order.status==='pending'" type="primary" @click="continuePay(order)">去支付</el-button>
                  <el-button v-if="order.status==='shipped'" type="success" @click="confirmReceive(order)">确认收货</el-button>
                  <el-button v-if="order.status==='completed' && !order.isReviewed" type="primary" plain @click="writeReview(order)">评价</el-button>
                  <el-button v-if="order.status==='pending'" type="danger" plain @click="cancelOrder(order)">取消订单</el-button>
                  <el-button v-if="['completed','cancelled'].includes(order.status)" type="danger" plain @click="deleteOrder(order)">删除订单</el-button>
                  <el-button type="info" plain @click="showOrderDetail(order)">详情</el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
        <div class="pagination-container" v-if="filteredOrders.length">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="filteredOrders.length"
            :page-size="ordersPageSize"
            :current-page="ordersCurrentPage"
            @current-change="handleOrdersPageChange"
          />
        </div>
        <!-- Add Order Detail Dialog -->
        <el-dialog
          title="订单详情"
          v-model="detailDialogVisible"
          width="600px"
          class="order-detail-dialog-root"
        >
          <div v-if="selectedOrder" class="order-detail-dialog">
            <div class="detail-section">
              <div class="detail-label">订单号:</div>
              <div class="detail-value">{{ selectedOrder.id }}</div>
            </div>
            <div class="detail-section">
              <div class="detail-label">状态:</div>
              <div class="detail-value">
                <el-tag :type="getStatusType(selectedOrder.status)">{{ getStatusText(selectedOrder.status) }}</el-tag>
              </div>
            </div>
            <div class="detail-section">
              <div class="detail-label">下单时间:</div>
              <div class="detail-value">{{ formatDate(selectedOrder.createTime) }}</div>
            </div>
            <div class="detail-section">
              <div class="detail-label">商品列表:</div>
              <div class="detail-items">
                <div v-for="item in selectedOrder.items" :key="item.id" class="detail-item">
                  <img :src="item.image" :alt="item.name" class="detail-item-image" />
                  <div class="detail-item-info">
                    <div class="detail-item-name">{{ item.name }}</div>
                    <div class="detail-item-quantity">数量：{{ item.quantity }}</div>
                    <div class="detail-item-price">单价：¥{{ item.price.toFixed(2) }}</div>
                    <div class="detail-item-subtotal">小计：¥{{ (item.price * item.quantity).toFixed(2) }}</div>
                  </div>
                </div>
              </div>
            </div>
             <div class="detail-section total-amount">
              <div class="detail-label">实付金额:</div>
              <div class="detail-value amount-value">¥{{ (selectedOrder.totalAmount ?? selectedOrder.total ?? 0).toFixed(2) }}</div>
            </div>
          </div>
        </el-dialog>
        <!-- 评价弹窗等保留原有 -->
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed, watch } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { StarFilled, Star, ArrowDown, Search, Document, ShoppingCart } from '@element-plus/icons-vue'

export default {
  name: 'Medicines',
  setup() {
    // 数据
    const medicines = ref([])
    const loading = ref(true)
    const searchQuery = ref('')
    const selectedCategory = ref('')
    const sortBy = ref('default')
    const currentPage = ref(1)
    const pageSize = ref(12)
    const dialogVisible = ref(false)
    const selectedMedicine = ref(null)
    const purchaseQuantity = ref(1)
    const store = useStore()
    const router = useRouter()
    const route = useRoute()
    const activeTab = ref('medicines')
    // 订单区数据
    const orders = ref([])
    const ordersLoading = ref(false)
    const orderSearchQuery = ref('')
    const statusFilter = ref('')
    const ordersCurrentPage = ref(1)
    const ordersPageSize = ref(5)
    const detailDialogVisible = ref(false)
    const reviewDialogVisible = ref(false)
    const selectedOrder = ref(null)
    const rateColors = ['#99A9BF', '#F7BA2A', '#FF9900']
    // 收藏相关
    const user = computed(() => store.state.user || { id: '' })
    const isAuthenticated = computed(() => store.state.isAuthenticated)
    const favorites = ref([])
    const cartItemCount = computed(() => store.getters.cartItemCount)

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    // 获取订单状态文本
    const getStatusText = (status) => {
      const statusMap = {
        pending: '待付款',
        paid: '待发货',
        shipped: '待收货',
        completed: '已完成',
        cancelled: '已取消'
      }
      return statusMap[status] || status
    }

    // 获取订单总商品数
    const getTotalItems = (order) => {
      return order.items?.reduce((total, item) => total + (item.quantity || 0), 0) || 0
    }

    // 获取订单小计
    const getSubtotal = (order) => {
      return order.items?.reduce((total, item) => total + (item.price || 0) * (item.quantity || 0), 0) || 0
    }

    // 获取运费
    const getShippingFee = (order) => {
      return order.shipping || 0
    }

    // 获取所有药品
    const fetchMedicines = async () => {
      try {
        loading.value = true
        const response = await axios.get('http://localhost:3000/medicines')
        medicines.value = response.data
      } catch (error) {
        ElMessage.error('获取药品列表失败')
        console.error('Error fetching medicines:', error)
      } finally {
        loading.value = false
      }
    }

    // 获取用户订单
    const fetchOrders = async () => {
      try {
        ordersLoading.value = true
        const userId = store.state.user?.id
        if (!userId) {
          ElMessage.warning('请先登录')
          return
        }
        const response = await axios.get(`http://localhost:3000/orders?userId=${userId}`)
        orders.value = response.data.map(order => ({
          ...order,
          createTime: order.createdAt
        }))
      } catch (error) {
        ElMessage.error('获取订单列表失败')
        console.error('Error fetching orders:', error)
      } finally {
        ordersLoading.value = false
      }
    }

    // 计算属性
    const categories = computed(() => {
      const categorySet = new Set(medicines.value.map(m => m.category))
      return Array.from(categorySet)
    })

    const filteredMedicines = computed(() => {
      let result = [...medicines.value]

      // 只显示上架的药品
      result = result.filter(medicine => medicine.status === 'active')

      // 应用搜索过滤
      if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase()
        result = result.filter(medicine => 
          medicine.name.toLowerCase().includes(query) ||
          medicine.category.toLowerCase().includes(query) ||
          medicine.description.toLowerCase().includes(query)
        )
      }

      // 应用分类过滤
      if (selectedCategory.value) {
        result = result.filter(medicine => medicine.category === selectedCategory.value)
      }

      // 应用排序
      switch (sortBy.value) {
        case 'priceAsc':
          result.sort((a, b) => a.price - b.price)
          break
        case 'priceDesc':
          result.sort((a, b) => b.price - a.price)
          break
        case 'sales':
          // 这里可以根据实际销量数据排序
          break
        default:
          // 默认排序，可以按照ID排序
          result.sort((a, b) => a.id - b.id)
      }

      return result
    })

    const totalMedicines = computed(() => filteredMedicines.value.length)

    const displayMedicines = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      return filteredMedicines.value.slice(start, end)
    })

    // 方法
    const handleSearch = () => {
      currentPage.value = 1
    }

    const handleCategoryChange = () => {
      currentPage.value = 1
    }

    const handleSort = () => {
      currentPage.value = 1
    }

    const handlePageChange = (page) => {
      currentPage.value = page
    }

    const showMedicineDetail = (medicine) => {
      selectedMedicine.value = medicine
      purchaseQuantity.value = 1
      dialogVisible.value = true
    }

    const addToCart = (medicine, quantity = 1) => {
      // 检查用户是否已登录
      if (!store.state.isAuthenticated) {
        ElMessage.warning('请先登录后再添加商品到购物车')
        router.push('/login')
        return
      }

      // 这里添加购物车逻辑
      const cartItem = {
        id: medicine.id,
        name: medicine.name,
        price: medicine.price,
        quantity: quantity,
        image: medicine.image
      }
      
      // 使用 Vuex mutation 来添加购物车
      store.commit('ADD_TO_CART', cartItem)
      
      ElMessage.success('已添加到购物车')
      dialogVisible.value = false
    }

    // 新增跳转方法
    const goToMedicines = () => {
      router.push('/medicines')
    }
    const goToOrders = () => {
      activeTab.value = 'orders'
      fetchOrders()
    }
    const goToCart = () => {
      router.push('/cart')
    }

    // 生命周期钩子
    onMounted(() => {
      fetchMedicines()
      loadFavorites()
      // 根据路由参数自动切换tab
      if (route.query.tab === 'orders') {
        activeTab.value = 'orders'
        fetchOrders() // 切换到订单tab时获取订单数据
      }
      // 如果初始tab就是orders，也要加载
      if (activeTab.value === 'orders') {
        fetchOrders()
      }
    })

    // 监听路由变化，支持前进/后退时tab切换
    watch(() => route.query.tab, (newTab) => {
      if (newTab === 'orders') {
        activeTab.value = 'orders'
        fetchOrders() // 切换到订单tab时获取订单数据
      } else if (newTab === 'medicines') {
        activeTab.value = 'medicines'
      }
    })

    // 监听activeTab变化
    watch(activeTab, (newTab) => {
      if (newTab === 'orders') {
        fetchOrders() // 切换到订单tab时获取订单数据
      }
    })

    // 订单相关计算属性和方法
    const filteredOrders = computed(() => {
      let result = Array.isArray(orders.value) ? [...orders.value] : [];
      // 搜索过滤
      if (orderSearchQuery.value) {
        const query = orderSearchQuery.value.toLowerCase();
        result = result.filter(order =>
          String(order.id).toLowerCase().includes(query) ||
          (order.items && order.items.some(item => item.name && item.name.toLowerCase().includes(query)))
        );
      }
      // 状态过滤
      if (statusFilter.value) {
        result = result.filter(order => order.status === statusFilter.value);
      }
      return result;
    });

    // 显示订单详情
    const showOrderDetail = (order) => {
      selectedOrder.value = order;
      detailDialogVisible.value = true;
    };

    const pagedOrders = computed(() => {
      const start = (ordersCurrentPage.value - 1) * ordersPageSize.value;
      const end = start + ordersPageSize.value;
      return filteredOrders.value.slice(start, end);
    });

    const ordersEmptyText = computed(() => {
      if (orderSearchQuery.value || statusFilter.value) {
        return '没有找到相关订单';
      }
      return '暂无订单';
    });

    // 订单分页、搜索等方法
    const handleOrdersPageChange = (page) => {
      ordersCurrentPage.value = page;
    };
    const handleOrderSearch = () => {
      ordersCurrentPage.value = 1;
    };

    const deleteOrder = async (order) => {
      try {
        await ElMessageBox.confirm('确定要删除该订单吗？删除后无法恢复。', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });
        await axios.delete(`http://localhost:3000/orders/${order.id}`);
        ElMessage.success('订单已删除');
        fetchOrders(); // 重新获取订单列表
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除订单失败');
          console.error('Error deleting order:', error);
        }
      }
    };

    const cancelOrder = async (order) => {
      try {
        await ElMessageBox.confirm('确定要取消该订单吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });
        // 只需要 PATCH status 字段
        await axios.patch(`http://localhost:3000/orders/${order.id}`, { status: 'cancelled' });
        ElMessage.success('订单已取消');
        fetchOrders(); // 重新获取订单列表
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('取消订单失败');
          console.error('Error cancelling order:', error);
        }
      }
    };

    // 加载收藏列表
    const loadFavorites = async () => {
      if (!user.value.id) return
      try {
        const res = await axios.get(`http://localhost:3000/users/${user.value.id}`)
        favorites.value = res.data.favorites || []
      } catch (e) {
        favorites.value = []
      }
    }

    // 判断商品是否已收藏
    const isFavorited = (medicine) => {
      return favorites.value.some(item => item.id === medicine.id)
    }

    // 收藏/取消收藏
    const toggleFavorite = async (medicine) => {
      if (!isAuthenticated.value) {
        ElMessage.warning('请先登录后再收藏商品')
        router.push('/login')
        return
      }
      let newFavorites
      if (isFavorited(medicine)) {
        // 取消收藏
        newFavorites = favorites.value.filter(item => item.id !== medicine.id)
      } else {
        // 添加收藏
        newFavorites = [...favorites.value, medicine]
      }
      try {
        await axios.patch(`http://localhost:3000/users/${user.value.id}`, { favorites: newFavorites })
        favorites.value = newFavorites
      } catch (e) {
        // 移除ElMessage.error
      }
    }

    // 监听user变化
    watch(() => store.state.user, () => {
      loadFavorites()
    })

    // 获取订单状态类型（用于el-tag）
    const getStatusType = (status) => {
      const types = {
        pending: 'warning',
        paid: 'primary',
        shipped: 'success',
        completed: 'info',
        cancelled: 'danger'
      }
      return types[status] || 'info'
    }

    // 用户确认收货
    const confirmReceive = async (order) => {
      try {
        await ElMessageBox.confirm('确认已收到货物？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });
        await axios.patch(`http://localhost:3000/orders/${order.id}`, { status: 'completed' });
        ElMessage.success('订单已完成，感谢您的确认！');
        fetchOrders();
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('确认收货失败');
        }
      }
    };

    return {
      medicines,
      loading,
      searchQuery,
      selectedCategory,
      sortBy,
      currentPage,
      pageSize,
      dialogVisible,
      selectedMedicine,
      purchaseQuantity,
      categories,
      totalMedicines,
      displayMedicines,
      handleSearch,
      handleCategoryChange,
      handleSort,
      handlePageChange,
      showMedicineDetail,
      addToCart,
      goToMedicines,
      goToOrders,
      activeTab,
      orders,
      ordersLoading,
      orderSearchQuery,
      statusFilter,
      ordersCurrentPage,
      ordersPageSize,
      detailDialogVisible,
      reviewDialogVisible,
      selectedOrder,
      rateColors,
      filteredOrders,
      pagedOrders,
      ordersEmptyText,
      handleOrdersPageChange,
      handleOrderSearch,
      fetchOrders,
      formatDate,
      getStatusText,
      getTotalItems,
      getSubtotal,
      getShippingFee,
      deleteOrder,
      cancelOrder,
      favorites,
      isFavorited,
      toggleFavorite,
      StarFilled,
      Star,
      showOrderDetail,
      ArrowDown,
      Search,
      Document,
      getStatusType,
      cartItemCount,
      goToCart,
      ShoppingCart,
      confirmReceive,
    }
  }
}
</script>

<style scoped>
.medicines-market {
  max-width: 1200px;
  margin: 0 auto;
  padding: 40px 0 0 0;
  min-height: 80vh;
}
.market-toolbar {
  display: flex;
  align-items: center;
  gap: 22px;
  margin-bottom: 32px;
  padding: 0 8px;
}
.toolbar-btn {
  height: 44px;
  border-radius: 24px !important;
  font-weight: 600;
  font-size: 16px;
  padding: 0 26px;
  display: flex;
  align-items: center;
  gap: 8px;
  background: #fff;
  border: 2px solid #409EFF;
  color: #409EFF;
  box-shadow: 0 2px 8px rgba(64,158,255,0.06);
  transition: all 0.2s;
  position: relative;
}
.toolbar-btn:hover {
  background: linear-gradient(90deg, #409EFF 0%, #36cfc9 100%);
  color: #fff;
  border-color: #409EFF;
  box-shadow: 0 4px 16px rgba(64,158,255,0.12);
  transform: translateY(-2px) scale(1.04);
}
.order-btn, .cart-btn {
  background: linear-gradient(90deg, #409EFF 0%, #36cfc9 100%);
  color: #fff;
  border: none;
}
.order-btn:hover, .cart-btn:hover {
  filter: brightness(1.08);
  box-shadow: 0 6px 20px rgba(64,158,255,0.18);
}
.cart-badge {
  position: absolute;
  top: -8px;
  right: -8px;
  background: #f56c6c;
  color: #fff;
  font-weight: bold;
  border-radius: 50%;
  min-width: 22px;
  height: 22px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  box-shadow: 0 2px 8px rgba(245,108,108,0.18);
}
.el-icon {
  font-size: 20px !important;
}
.market-list {
  margin-bottom: 32px;
}
.market-card {
  position: relative;
  border-radius: 18px;
  overflow: hidden;
  box-shadow: 0 4px 24px rgba(64,158,255,0.10);
  transition: box-shadow 0.2s, transform 0.2s;
  margin-bottom: 24px;
  display: flex;
  flex-direction: column;
  height: 100%;
  background: #fff;
}
.market-card:hover {
  box-shadow: 0 8px 32px rgba(64,158,255,0.18);
  transform: translateY(-4px) scale(1.03);
}
.market-img-wrap {
  height: 180px;
  background: #f8fafb;
  display: flex;
  align-items: center;
  justify-content: center;
  border-bottom: 1px solid #f0f0f0;
}
.market-img-wrap img {
  max-width: 90%;
  max-height: 90%;
  object-fit: contain;
  transition: transform 0.2s;
}
.market-info {
  padding: 18px 12px 12px 12px;
  display: flex;
  flex-direction: column;
  flex: 1;
  align-items: flex-start;
}
.market-title {
  font-size: 17px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
  min-height: 40px;
}
.market-price-row {
  display: flex;
  align-items: baseline;
  gap: 8px;
  margin-bottom: 10px;
}
.market-price {
  color: #409EFF;
  font-size: 20px;
  font-weight: 700;
}
.market-origin {
  color: #bbb;
  font-size: 14px;
  text-decoration: line-through;
}
.market-cart-btn {
  border-radius: 18px;
  font-weight: 500;
  margin-top: 4px;
}
.pagination-container {
  text-align: center;
  margin: 32px 0 0 0;
  background: transparent;
}
.market-btn-row {
  display: flex;
  gap: 8px;
  margin-top: 8px;
  align-items: center;
}
.market-detail-btn {
  border-radius: 18px;
  font-weight: 500;
}
.market-fav-float {
  position: absolute;
  top: 18px;
  right: 18px;
  z-index: 2;
  cursor: pointer;
  background: rgba(255,255,255,0.85);
  border-radius: 50%;
  box-shadow: 0 2px 8px rgba(64,158,255,0.10);
  padding: 4px;
  transition: box-shadow 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
}
.fav-float-icon {
  font-size: 28px;
  color: #bbb;
  transition: color 0.2s, transform 0.2s, text-shadow 0.2s;
}
.fav-float-icon.active {
  color: #409EFF;
  text-shadow: 0 0 8px #b3d8ff;
  transform: scale(1.15);
}
.market-fav-float:hover .fav-float-icon {
  color: #409EFF;
  transform: scale(1.2) rotate(-10deg);
}
@media (max-width: 900px) {
  .market-toolbar {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }
  .market-list {
    margin-bottom: 16px;
  }
}
@media (max-width: 600px) {
  .market-img-wrap {
    height: 120px;
  }
  .market-card {
    border-radius: 10px;
  }
}
.detail-dialog-root >>> .el-dialog__body {
  padding: 0 32px 32px 32px;
  background: #f8fafb;
  border-radius: 18px;
}
.detail-dialog {
  display: flex;
  gap: 32px;
  align-items: flex-start;
}
.detail-left {
  flex: 0 0 260px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  border-radius: 14px;
  box-shadow: 0 2px 12px rgba(64,158,255,0.08);
  padding: 24px;
  min-height: 320px;
}
.detail-left img {
  max-width: 200px;
  max-height: 260px;
  object-fit: contain;
  border-radius: 10px;
  background: #f6faff;
}
.detail-right {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.detail-title {
  font-size: 26px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 4px;
}
.detail-price-row {
  display: flex;
  align-items: baseline;
  gap: 12px;
  margin-bottom: 8px;
}
.detail-price {
  color: #409EFF;
  font-size: 24px;
  font-weight: 700;
}
.detail-origin {
  color: #bbb;
  font-size: 16px;
  text-decoration: line-through;
}
.detail-tags {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  margin-bottom: 8px;
}
.detail-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}
.detail-desc-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(64,158,255,0.06);
  padding: 18px 16px 10px 16px;
  margin-top: 8px;
}
.detail-desc-card h3 {
  font-size: 17px;
  color: #409EFF;
  margin-bottom: 8px;
}
.detail-desc-card p {
  color: #606266;
  font-size: 15px;
  margin-bottom: 6px;
}
.detail-usage {
  color: #909399;
  font-size: 14px;
  margin-top: 4px;
}
@media (max-width: 700px) {
  .detail-dialog {
    flex-direction: column;
    gap: 16px;
  }
  .detail-left {
    min-height: 180px;
    padding: 12px;
    max-width: 100%;
  }
  .detail-left img {
    max-width: 100%;
    max-height: 180px;
  }
}
.order-btn {
  margin-left: auto;
  border-radius: 20px;
  font-weight: 500;
  height: 38px;
  display: flex;
  align-items: center;
}
.orders-page {
  max-width: 1100px;
  margin: 0 auto;
  padding: 32px 0 0 0;
}
.orders-toolbar {
  display: flex;
  align-items: center;
  gap: 18px;
  margin-bottom: 32px;
}
.orders-search {
  width: 260px;
  margin-left: auto;
}
.order-card {
  border-radius: 16px;
  box-shadow: 0 4px 18px rgba(64,158,255,0.08);
  margin-bottom: 24px;
  padding: 0 0 12px 0;
  transition: box-shadow 0.2s, transform 0.2s;
}
.order-card:hover {
  box-shadow: 0 8px 32px rgba(64,158,255,0.16);
  transform: translateY(-2px) scale(1.01);
}
.order-header {
  display: flex;
  align-items: center;
  gap: 18px;
  padding: 18px 24px 10px 24px;
  background: #f8fafb;
  border-radius: 16px 16px 0 0;
  font-size: 15px;
  font-weight: 500;
}
.order-header .order-time {
  margin-left: auto;
  color: #888;
  font-size: 13px;
}
.order-items {
  display: flex;
  flex-wrap: wrap;
  gap: 18px;
  padding: 18px 24px 0 24px;
}
.order-item {
  display: flex;
  align-items: center;
  gap: 16px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(64,158,255,0.06);
  padding: 10px 18px;
  min-width: 260px;
  flex: 1 1 260px;
}
.item-image {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  object-fit: cover;
  background: #f6faff;
}
.item-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}
.item-name {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
}
.item-quantity, .item-price, .item-subtotal {
  font-size: 13px;
  color: #888;
}
.order-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 24px 0 24px;
  border-top: 1px solid #f0f0f0;
  margin-top: 8px;
}
.order-summary {
  font-size: 16px;
  color: #303133;
}
.order-amount {
  color: #409EFF;
  font-size: 20px;
  font-weight: 700;
  margin-left: 8px;
}
.order-actions {
  display: flex;
  gap: 10px;
}
.order-actions .el-button {
  border-radius: 18px;
  font-weight: 500;
  min-width: 80px;
}
@media (max-width: 900px) {
  .orders-toolbar {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }
  .order-items {
    flex-direction: column;
    gap: 10px;
    padding: 12px 8px 0 8px;
  }
  .order-footer {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
    padding: 12px 8px 0 8px;
  }
}
.back-btn {
  margin-right: 16px;
  border-radius: 20px;
  font-weight: 500;
}
.cart-btn {
  margin-left: 12px;
  border-radius: 20px;
  font-weight: 500;
  position: relative;
}
.order-detail-dialog-root >>> .el-dialog__body {
  padding: 0 32px 32px 32px;
  background: #f8fafb;
  border-radius: 18px;
}
.order-detail-dialog {
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.detail-section {
  display: flex;
  align-items: center;
  gap: 12px;
}
.detail-label {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}
.detail-value {
  font-size: 14px;
  color: #606266;
}
.detail-items {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.detail-item {
  display: flex;
  align-items: center;
  gap: 12px;
}
.detail-item-image {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  object-fit: cover;
  background: #f6faff;
}
.detail-item-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}
.detail-item-name {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
}
.detail-item-quantity {
  font-size: 13px;
  color: #888;
}
.detail-item-price {
  font-size: 13px;
  color: #888;
}
.detail-item-subtotal {
  font-size: 13px;
  color: #888;
}
.total-amount {
  font-size: 16px;
  font-weight: 700;
  color: #409EFF;
}
.amount-value {
  margin-left: 8px;
}
</style> 